using B.S.Data.MES.API.Applications.ShenchanInfoApplication.Commands;
using B.S.Domain.Dto.ShenchanDto;
using B.S.Requst;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace B.S.Data.MES.API.Controllers
{
    /// <summary>
    /// 生产信息管理控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ShenchanInfoController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<ShenchanInfoController> _logger;

        public ShenchanInfoController(IMediator mediator, ILogger<ShenchanInfoController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 创建生产信息
        /// </summary>
        /// <param name="shenchanInfo">生产信息创建DTO</param>
        /// <returns>生产信息ID</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<string>> CreateShenchanInfo([FromBody] ShenchanInfoCreateDTO shenchanInfo)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage);
                    
                    return new APIRequst<string>
                    {
                        Code = RequstCode.失败,
                        Msg = $"数据验证失败: {string.Join(", ", errors)}",
                        Data = string.Empty
                    };
                }

                var command = new CreateShenchanInfoCommand { ShenchanInfo = shenchanInfo };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("创建生产信息请求处理完成，结果: {Code}", result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建生产信息异常: {Message}", ex.Message);
                return new APIRequst<string>
                {
                    Code = RequstCode.失败,
                    Msg = $"创建生产信息异常: {ex.Message}",
                    Data = string.Empty
                };
            }
        }

        /// <summary>
        /// 更新生产信息
        /// </summary>
        /// <param name="shenchanInfo">生产信息更新DTO</param>
        /// <returns>更新结果</returns>
        [HttpPut]
        [AllowAnonymous]
        public async Task<APIRequst<int>> UpdateShenchanInfo([FromBody] ShenchanInfoUpdateDTO shenchanInfo)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var errors = ModelState.Values
                        .SelectMany(v => v.Errors)
                        .Select(e => e.ErrorMessage);
                    
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = $"数据验证失败: {string.Join(", ", errors)}",
                        Data = 0
                    };
                }

                var command = new UpdateShenchanInfoCommand { ShenchanInfo = shenchanInfo };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("更新生产信息请求处理完成，结果: {Code}", result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新生产信息异常: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"更新生产信息异常: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 删除生产信息
        /// </summary>
        /// <param name="sid">生产信息ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{sid}")]
        [AllowAnonymous]
        public async Task<APIRequst<int>> DeleteShenchanInfo([FromRoute] string sid)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(sid))
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "生产信息ID不能为空",
                        Data = 0
                    };
                }

                var command = new DeleteShenchanInfoCommand { SID = sid };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("删除生产信息请求处理完成，SID: {SID}, 结果: {Code}", sid, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除生产信息异常: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"删除生产信息异常: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 批量删除生产信息
        /// </summary>
        /// <param name="sids">生产信息ID列表</param>
        /// <returns>删除结果</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<int>> BatchDeleteShenchanInfo([FromBody] List<string> sids)
        {
            try
            {
                if (sids == null || !sids.Any())
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "请选择要删除的生产信息",
                        Data = 0
                    };
                }

                var command = new BatchDeleteShenchanInfoCommand { SIDs = sids };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("批量删除生产信息请求处理完成，数量: {Count}, 结果: {Code}", sids.Count, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除生产信息异常: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"批量删除生产信息异常: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 查询生产信息列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>生产信息列表</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<APIPageing<List<ShenchanInfoDetailDTO>>>> QueryShenchanInfoList([FromBody] ShenchanInfoQueryDTO query)
        {
            try
            {
                var command = new QueryShenchanInfoListCommand { Query = query ?? new ShenchanInfoQueryDTO() };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("查询生产信息列表请求处理完成，结果: {Code}", result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询生产信息列表异常: {Message}", ex.Message);
                return new APIRequst<APIPageing<List<ShenchanInfoDetailDTO>>>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询生产信息列表异常: {ex.Message}",
                    Data = new APIPageing<List<ShenchanInfoDetailDTO>>
                    {
                        Total = 0,
                        TotalCount = 0,
                        Data = new List<ShenchanInfoDetailDTO>()
                    }
                };
            }
        }

        /// <summary>
        /// 根据ID查询生产信息详情
        /// </summary>
        /// <param name="sid">生产信息ID</param>
        /// <returns>生产信息详情</returns>
        [HttpGet("{sid}")]
        [AllowAnonymous]
        public async Task<APIRequst<ShenchanInfoDetailDTO>> GetShenchanInfoById([FromRoute] string sid)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(sid))
                {
                    return new APIRequst<ShenchanInfoDetailDTO>
                    {
                        Code = RequstCode.失败,
                        Msg = "生产信息ID不能为空",
                        Data = null!
                    };
                }

                var command = new GetShenchanInfoByIdCommand { SID = sid };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("查询生产信息详情请求处理完成，SID: {SID}, 结果: {Code}", sid, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询生产信息详情异常: {Message}", ex.Message);
                return new APIRequst<ShenchanInfoDetailDTO>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询生产信息详情异常: {ex.Message}",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 根据产品物料ID查询生产信息
        /// </summary>
        /// <param name="productId">产品物料ID</param>
        /// <returns>生产信息列表</returns>
        [HttpGet("{productId}")]
        [AllowAnonymous]
        public async Task<APIRequst<List<ShenchanInfoDetailDTO>>> GetShenchanInfoByProductId([FromRoute] int productId)
        {
            try
            {
                if (productId <= 0)
                {
                    return new APIRequst<List<ShenchanInfoDetailDTO>>
                    {
                        Code = RequstCode.失败,
                        Msg = "产品物料ID无效",
                        Data = new List<ShenchanInfoDetailDTO>()
                    };
                }

                var command = new GetShenchanInfoByProductIdCommand { ProductId = productId };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("根据产品物料ID查询生产信息请求处理完成，ProductId: {ProductId}, 结果: {Code}", productId, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据产品物料ID查询生产信息异常: {Message}", ex.Message);
                return new APIRequst<List<ShenchanInfoDetailDTO>>
                {
                    Code = RequstCode.失败,
                    Msg = $"根据产品物料ID查询生产信息异常: {ex.Message}",
                    Data = new List<ShenchanInfoDetailDTO>()
                };
            }
        }

        /// <summary>
        /// 根据工序路线ID查询生产信息
        /// </summary>
        /// <param name="processrouteId">工序路线ID</param>
        /// <returns>生产信息列表</returns>
        [HttpGet("{processrouteId}")]
        [AllowAnonymous]
        public async Task<APIRequst<List<ShenchanInfoDetailDTO>>> GetShenchanInfoByProcessrouteId([FromRoute] int processrouteId)
        {
            try
            {
                if (processrouteId <= 0)
                {
                    return new APIRequst<List<ShenchanInfoDetailDTO>>
                    {
                        Code = RequstCode.失败,
                        Msg = "工序路线ID无效",
                        Data = new List<ShenchanInfoDetailDTO>()
                    };
                }

                var command = new GetShenchanInfoByProcessrouteIdCommand { ProcessrouteId = processrouteId };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("根据工序路线ID查询生产信息请求处理完成，ProcessrouteId: {ProcessrouteId}, 结果: {Code}", processrouteId, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据工序路线ID查询生产信息异常: {Message}", ex.Message);
                return new APIRequst<List<ShenchanInfoDetailDTO>>
                {
                    Code = RequstCode.失败,
                    Msg = $"根据工序路线ID查询生产信息异常: {ex.Message}",
                    Data = new List<ShenchanInfoDetailDTO>()
                };
            }
        }

        /// <summary>
        /// 获取生产统计信息
        /// </summary>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <param name="productId">产品物料ID（可选）</param>
        /// <returns>生产统计信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<APIRequst<ShenchanStatisticsDTO>> GetShenchanStatistics(
            [FromQuery] DateTime? startDate = null,
            [FromQuery] DateTime? endDate = null,
            [FromQuery] int? productId = null)
        {
            try
            {
                var command = new GetShenchanStatisticsCommand 
                { 
                    StartDate = startDate,
                    EndDate = endDate,
                    ProductId = productId
                };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("获取生产统计信息请求处理完成，结果: {Code}", result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产统计信息异常: {Message}", ex.Message);
                return new APIRequst<ShenchanStatisticsDTO>
                {
                    Code = RequstCode.失败,
                    Msg = $"获取生产统计信息异常: {ex.Message}",
                    Data = new ShenchanStatisticsDTO()
                };
            }
        }

        /// <summary>
        /// 恢复删除的生产信息
        /// </summary>
        /// <param name="sid">生产信息ID</param>
        /// <returns>恢复结果</returns>
        [HttpPut("{sid}")]
        [AllowAnonymous]
        public async Task<APIRequst<int>> RestoreShenchanInfo([FromRoute] string sid)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(sid))
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "生产信息ID不能为空",
                        Data = 0
                    };
                }

                var command = new RestoreShenchanInfoCommand { SID = sid };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("恢复生产信息请求处理完成，SID: {SID}, 结果: {Code}", sid, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "恢复生产信息异常: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"恢复生产信息异常: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 批量恢复删除的生产信息
        /// </summary>
        /// <param name="sids">生产信息ID列表</param>
        /// <returns>恢复结果</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<int>> BatchRestoreShenchanInfo([FromBody] List<string> sids)
        {
            try
            {
                if (sids == null || !sids.Any())
                {
                    return new APIRequst<int>
                    {
                        Code = RequstCode.失败,
                        Msg = "请选择要恢复的生产信息",
                        Data = 0
                    };
                }

                var command = new BatchRestoreShenchanInfoCommand { SIDs = sids };
                var result = await _mediator.Send(command);
                
                _logger.LogInformation("批量恢复生产信息请求处理完成，数量: {Count}, 结果: {Code}", sids.Count, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量恢复生产信息异常: {Message}", ex.Message);
                return new APIRequst<int>
                {
                    Code = RequstCode.失败,
                    Msg = $"批量恢复生产信息异常: {ex.Message}",
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 创建测试数据
        /// </summary>
        /// <returns>创建结果</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<string>> CreateTestData()
        {
            try
            {
                // 创建测试生产信息
                var testData = new ShenchanInfoCreateDTO
                {
                    Productid = 1,
                    Id = 1,
                    ProductName = "测试产品A",
                    ProductStandard = "标准规格",
                    ProductCount = 100,
                    ProductColor = "蓝色"
                };

                var command = new CreateShenchanInfoCommand { ShenchanInfo = testData };
                var result = await _mediator.Send(command);
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建测试数据异常: {Message}", ex.Message);
                return new APIRequst<string>
                {
                    Code = RequstCode.失败,
                    Msg = $"创建测试数据异常: {ex.Message}",
                    Data = string.Empty
                };
            }
        }

        /// <summary>
        /// 简化查询 - 只查询生产信息表，不关联其他表
        /// </summary>
        /// <returns>生产信息列表</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<object> SimpleQuery()
        {
            return await _mediator.Send(new SimpleQueryCommand());
        }

        /// <summary>
        /// 调试查询 - 检查数据库中的数据情况
        /// </summary>
        /// <returns>调试信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<object> DebugQuery()
        {
            return await _mediator.Send(new DebugQueryCommand());
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>健康状态</returns>
        [HttpGet]
        [AllowAnonymous]
        public APIRequst<object> HealthCheck()
        {
            try
            {
                return new APIRequst<object>
                {
                    Code = RequstCode.成功,
                    Msg = "生产信息管理服务运行正常",
                    Data = new
                    {
                        Service = "生产信息管理",
                        Status = "Healthy",
                        Timestamp = DateTime.Now,
                        Features = new[]
                        {
                            "生产信息增删改查",
                            "关联产品物料查询",
                            "关联工序路线查询",
                            "生产统计分析",
                            "批量操作"
                        }
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "健康检查失败: {Message}", ex.Message);
                return new APIRequst<object>
                {
                    Code = RequstCode.失败,
                    Msg = $"健康检查失败: {ex.Message}",
                    Data = new { Status = "Unhealthy", Error = ex.Message }
                };
            }
        }

        /// <summary>
        /// 详细调试查询 - 逐步分析主查询问题
        /// </summary>
        /// <returns>详细调试信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<APIRequst<object>> DetailedDebugQuery()
        {
            return await _mediator.Send(new DetailedDebugQueryCommand());
        }

        /// <summary>
        /// 获取工序路线下拉框数据
        /// </summary>
        /// <returns>工序路线下拉框数据</returns>
        [HttpGet]
        public async Task<APIRequst<List<ProcessrouteDropdownDTO>>> GetProcessrouteDropdown()
        {
            return await _mediator.Send(new GetProcessrouteDropdownCommand());
        }
    }
}
